package com.mhc.suzuki.service.impl;

/**
 * Created by HW
 * on 2017/8/17 10:12.
 */

import com.alibaba.fastjson.JSON;
import com.mhc.haval.security.model.User;
import com.mhc.suzuki.api.service.IDataDictService;
import com.mhc.suzuki.bo.*;
import com.mhc.suzuki.constant.ErrorCodeEnum;
import com.mhc.suzuki.constant.IsDeletedEnum;
import com.mhc.suzuki.dal.mapper.ext.*;
import com.mhc.suzuki.dal.model.*;
import com.mhc.suzuki.dal.query.*;
import com.mhc.suzuki.exception.SuzukiCommonException;
import com.mhc.suzuki.service.OrderGeneralInfoService;
import com.mhc.suzuki.vo.DataDictVO;
import com.subaru.common.util.BeanCopierUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;


import java.util.*;

@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class OrderGeneralInfoServiceImpl implements OrderGeneralInfoService{

    @Autowired
    private OrderExtMapper orderExtMapper;

    @Autowired
    private InsuranceInfoExtMapper insuranceInfoExtMapper;

    @Autowired
    private AccidentExtMapper accidentExtMapper;

    @Autowired
    private CarInfoExtMapper carInfoExtMapper;

    @Autowired
    private NotaryMortgageExtMapper notaryMortgageExtMapper;

    @Autowired
    private ContractSubmitExtMapper contractSubmitExtMapper;

    @Autowired
    private PostBankCardExtMapper postBankCardExtMapper;

    @Autowired
    private RefundDepositExtMapper refundDepositExtMapper;

    @Autowired
    private LoanClearExtMapper loanClearExtMapper;

    @Autowired
    private LoanInfoExtMapper loanInfoExtMapper;

    @Autowired
    private IDataDictService iDataDictService;

    @Autowired
    private DataDictExtMapper dataDictExtMapper;


    /**
     * 获取订单综合信息
     * @param orderNo
     * @return
     * @throws SuzukiCommonException
     */
    @Override
    public GeneralOrderInfoBO getGeneralOrderInfoByOrderNo(String orderNo) throws SuzukiCommonException{
        GeneralOrderInfoBO generalOrderInfoBO =  new GeneralOrderInfoBO();
        /*放款信息查询*/
        log.info("正在查询放款信息...");
        Map<String, Object> paramMap = new HashMap<>(64);
        paramMap.put("orderNo",orderNo);       //订单号
        paramMap.put("isDeleted", IsDeletedEnum.NORMAL.getCode());       //未删除
        OrderLoanInfoBO  orderLoanInfoBO = orderExtMapper.selectGeneralInfoByOrderNo(paramMap);
        log.info("放款信息获取完成...");
        generalOrderInfoBO.setOrderNo(orderNo);
        generalOrderInfoBO.setLoanInfo(orderLoanInfoBO);

        /**查询保险信息**/
        log.info("正在查询保险信息...");
        List<GeneralInsuranceInfoBO> generalInsuranceInfoBOS = getInsuranceInfoByOrderNo(orderNo);
        if(!CollectionUtils.isEmpty(generalInsuranceInfoBOS)){
            generalOrderInfoBO.setInsurance(generalInsuranceInfoBOS);
        }
        log.info("保险信息查询完成...");

        /*查询出险信息*/
        log.info("正在查询出险信息...");
        GeneralAccidentBO generalAccidentBO = getAccidentInfoByOrderNo(orderNo);
        if(generalAccidentBO!=null){
            generalOrderInfoBO.setAccident(generalAccidentBO);
        }
        log.info("出险信息查询完成...");

        /*车辆信息*/
        log.info("正在查询车辆信息...");
        GeneralCarInfoBO generalCarInfoBO = getCarInfoByOrderNo(orderNo);
        if(generalCarInfoBO != null){
            generalOrderInfoBO.setCarInfo(generalCarInfoBO);
        }
        log.info("车辆信息查询完成...");

        /*查询公证抵押信息*/
        log.info("正在查询公证抵押信息...");
        GeneralNotaryMortgageBO generalNotaryMortgageBO = getNotaryMortgageByOrderNo(orderNo);
        if (generalNotaryMortgageBO != null){
            generalOrderInfoBO.setNotaryMortgage(generalNotaryMortgageBO);
        }
        log.info("公证抵押信息查询完成...");

        /*查询合同齐全信息*/
        log.info("正在查询合同齐全信息...");
        GeneralContractSubmitBO generalContractSubmitBO = getContractSubmitByOrderNo(orderNo);
        if (generalContractSubmitBO != null){
            generalOrderInfoBO.setContractSubmit(generalContractSubmitBO);
        }
        log.info("合同齐全信息查询完成...");

        /*寄卡信息查询*/
        log.info("正在查询寄卡信息...");
        GeneralPostBankCardBO generalPostBankCardBO = getPostBankCardByOrderNo(orderNo);
        if (generalPostBankCardBO != null){
            generalOrderInfoBO.setPostBankCardForm(generalPostBankCardBO);
        }
        log.info("寄卡信息查询完成...");

        /*退保证金信息*/
        log.info("正在查询退保证金信息...");
        GeneralRefundDepositBO generalRefundDepositBO = getRefundDepositByOrderNo(orderNo);
        if (generalRefundDepositBO != null){
            generalOrderInfoBO.setRefundDeposit(generalRefundDepositBO);
        }
        log.info("退保证金信息查询完成...");

        /*结清信息*/
        log.info("正在查询结清信息...");
        GeneralLoanClearBO generalLoanClearBO = getLoanClearByOrderNo(orderNo);
        if (generalLoanClearBO != null){
            generalOrderInfoBO.setLoanClear(generalLoanClearBO);
        }
        log.info("结清信息查询完成...");

        return generalOrderInfoBO;
    }


    /**
     * 根据订单号获取保险信息列表
     * @param orderNo
     * @return
     */
    private List<GeneralInsuranceInfoBO> getInsuranceInfoByOrderNo(String orderNo) {
        InsuranceInfoQuery insuranceInfoQuery = new InsuranceInfoQuery();
        insuranceInfoQuery.createCriteria().andOrderNoEqualTo(orderNo)
                .andIsDeletedEqualTo(IsDeletedEnum.NORMAL.getCode());
        List<InsuranceInfoDO> insuranceInfoDOS = insuranceInfoExtMapper.selectByQuery(insuranceInfoQuery);
        List<GeneralInsuranceInfoBO> generalInsuranceInfoBOS = new ArrayList<>();
        /*一条订单对应保险记录最多两条*/
        if(insuranceInfoDOS.size() <= 2 ){
            if(!insuranceInfoDOS.isEmpty()){
                for(InsuranceInfoDO insuranceInfoDO : insuranceInfoDOS){
                    GeneralInsuranceInfoBO generalInsuranceInfoBO = new GeneralInsuranceInfoBO();
                    BeanCopierUtil.copy(insuranceInfoDO, generalInsuranceInfoBO);
                    generalInsuranceInfoBOS.add(generalInsuranceInfoBO);
                }
                return generalInsuranceInfoBOS;
            }else {
                return generalInsuranceInfoBOS;
            }
        }
        log.error("保险信息获取错误...");
        throw new SuzukiCommonException(ErrorCodeEnum.INSURANCE_INFO_TOO_MORE);
    }

    /**
     * 根据订单号获取出险信息
     * @param orderNo
     * @return
     */
    private GeneralAccidentBO getAccidentInfoByOrderNo(String orderNo) throws SuzukiCommonException{
        AccidentQuery accidentQuery = new AccidentQuery();
        accidentQuery.createCriteria().andOrderNoEqualTo(orderNo)
                .andIsDeletedEqualTo(IsDeletedEnum.NORMAL.getCode());
        List<AccidentDO> accidentDOS = accidentExtMapper.selectByQuery(accidentQuery);
        GeneralAccidentBO generalAccidentBO = new GeneralAccidentBO();
        if(!CollectionUtils.isEmpty(accidentDOS)){
            BeanCopierUtil.copy(accidentDOS.get(0), generalAccidentBO);
        }
        return generalAccidentBO;
    }

    /**
     * 根据订单号获取车辆信息
     * @param orderNo
     * @return
     */
    private GeneralCarInfoBO getCarInfoByOrderNo(String orderNo) throws SuzukiCommonException{
        CarInfoQuery carInfoQuery = new CarInfoQuery();
        carInfoQuery.createCriteria().andOrderNoEqualTo(orderNo);
        List<CarInfoDO> carInfoDOS = carInfoExtMapper.selectByQuery(carInfoQuery);
        GeneralCarInfoBO generalCarInfoBO = new GeneralCarInfoBO();
        if(!CollectionUtils.isEmpty(carInfoDOS)){
            BeanCopierUtil.copy(carInfoDOS.get(0), generalCarInfoBO);
        }
        log.info("完成获取车辆信息...");
        return generalCarInfoBO;
    }

    /**
     * 根据订单号获取公证抵押信息
     * @param orderNo
     * @return
     */
    private GeneralNotaryMortgageBO getNotaryMortgageByOrderNo(String orderNo) throws SuzukiCommonException{
        NotaryMortgageQuery notaryMortgageQuery = new NotaryMortgageQuery();
        notaryMortgageQuery.createCriteria().andOrderNoEqualTo(orderNo)
                .andIsDeletedNotEqualTo(IsDeletedEnum.DELETED.getCode());
        List<NotaryMortgageDO> notaryMortgageDOS = notaryMortgageExtMapper.selectByQuery(notaryMortgageQuery);
        GeneralNotaryMortgageBO generalNotaryMortgageBO =  new GeneralNotaryMortgageBO();
        if(!CollectionUtils.isEmpty(notaryMortgageDOS)){
            BeanCopierUtil.copy(notaryMortgageDOS.get(0), generalNotaryMortgageBO);
        }
        log.info("完成获取公证抵押信息...");
        return generalNotaryMortgageBO;
    }

    /**
     * 根据订单号获取合同齐全信息
     * @param orderNo
     * @return
     */
    private GeneralContractSubmitBO getContractSubmitByOrderNo(String orderNo) throws SuzukiCommonException{
        ContractSubmitQuery contractSubmitQuery = new ContractSubmitQuery();
        contractSubmitQuery.createCriteria().andOrderNoEqualTo(orderNo)
                .andIsDeletedEqualTo(IsDeletedEnum.NORMAL.getCode());
        List<ContractSubmitDO> contractSubmitDOS = contractSubmitExtMapper.selectByQuery(contractSubmitQuery);
        GeneralContractSubmitBO generalContractSubmitBO = new GeneralContractSubmitBO();
        if(!CollectionUtils.isEmpty(contractSubmitDOS)){
            BeanCopierUtil.copy(contractSubmitDOS.get(0), generalContractSubmitBO);
        }
        log.info("完成获取合同齐全信息...");
        return generalContractSubmitBO;
    }

    /**
     * 根据订单号获取综合录入页面寄卡信息
     * @param orderNo
     * @return
     */
    private GeneralPostBankCardBO getPostBankCardByOrderNo(String orderNo) throws SuzukiCommonException{
        PostBankCardQuery postBankCardQuery = new PostBankCardQuery();
        postBankCardQuery.createCriteria().andOrderNoEqualTo(orderNo)
                .andIsDeletedNotEqualTo(IsDeletedEnum.DELETED.getCode());
        List<PostBankCardDO> postBankCardDOS = postBankCardExtMapper.selectByQuery(postBankCardQuery);
        GeneralPostBankCardBO generalPostBankCardBO =  new GeneralPostBankCardBO();
        if(!CollectionUtils.isEmpty(postBankCardDOS)){
            BeanCopierUtil.copy(postBankCardDOS.get(0), generalPostBankCardBO);
        }
        log.info("完成获取寄卡信息...");
        return generalPostBankCardBO;
    }

    /**
     * 根据订单号获取退保证金信息
     * @param orderNo
     * @return
     */
    public GeneralRefundDepositBO getRefundDepositByOrderNo(String orderNo) {
        Map<String, Object> query = new HashMap<>(64);
        query.put("orderNo", orderNo);
        List<GeneralRefundDepositBO> generalRefundDepositBOS = refundDepositExtMapper.selectGeneralRefundDepositByQuery(query);
        GeneralRefundDepositBO generalRefundDepositBO = new GeneralRefundDepositBO();
        if(!CollectionUtils.isEmpty(generalRefundDepositBOS)){
            generalRefundDepositBO = generalRefundDepositBOS.get(0);
        }
        log.info("完成获取退保证金信息...");
        return generalRefundDepositBO;
    }


    /**
     * 根据订单号获取结清信息
     * @param orderNo
     * @return
     */
    public GeneralLoanClearBO getLoanClearByOrderNo(String orderNo) {
        LoanClearQuery loanClearQuery = new LoanClearQuery();
        loanClearQuery.createCriteria().andOrderNoEqualTo(orderNo)
                .andIsDeletedNotEqualTo(IsDeletedEnum.DELETED.getCode());
        List<LoanClearDO> loanClearDOS = loanClearExtMapper.selectByQuery(loanClearQuery);
        GeneralLoanClearBO generalLoanClearBO = new GeneralLoanClearBO();
        if(!CollectionUtils.isEmpty(loanClearDOS)){
            BeanCopierUtil.copy(loanClearDOS.get(0), generalLoanClearBO);
        }
        log.info("完成获取结清信息...");
        return generalLoanClearBO;
    }


    /**
     * 出险信息录入
     * @param generalAccidentBO
     * @return
     * @throws SuzukiCommonException
     */
    @Override
    @Transactional
    public Boolean inputAccidentInfo(GeneralAccidentBO generalAccidentBO) throws SuzukiCommonException {
        log.info("开始录入出险信息...");
        AccidentDO accidentDO = new AccidentDO();
        BeanCopierUtil.copy(generalAccidentBO, accidentDO);
        if(generalAccidentBO.getAccidentId()==null){
            log.info("新增出险信息...");
            accidentDO.setIsDeleted(IsDeletedEnum.NORMAL.getCode());
            if (accidentExtMapper.insertSelective(accidentDO) != 1) {
                throw new SuzukiCommonException(ErrorCodeEnum.INSERT_OR_UPDATA_ERROR);
            }
        }else {
            log.info("更新出险信息...");
            if (accidentExtMapper.updateByPrimaryKeySelective(accidentDO) != 1) {
                throw new SuzukiCommonException(ErrorCodeEnum.INSERT_OR_UPDATA_ERROR);
            }
        }
        log.info("录入出险信息完成...");
        return true;
    }


    /**
     * 车辆信息录入
     * @param generalCarInfoBO
     * @return
     * @throws SuzukiCommonException
     */
    @Override
    @Transactional
    public Boolean inputCarInfo(GeneralCarInfoBO generalCarInfoBO) throws SuzukiCommonException {
        log.info("正在录入车辆信息...");
        if(generalCarInfoBO.getCarId() == null){
            log.error("车辆信息有误，缺少carId字段...");
            throw new SuzukiCommonException(ErrorCodeEnum.CARINFO_NOT_EXIST);
        }
        CarInfoDO carInfoDO = new CarInfoDO();
        BeanCopierUtil.copy(generalCarInfoBO, carInfoDO);
        log.info("正在更新车辆信息...");
        if( carInfoExtMapper.updateByPrimaryKeySelective(carInfoDO) != 1) {
            throw new SuzukiCommonException(ErrorCodeEnum.INSERT_OR_UPDATA_ERROR);
        }
        log.info("更新车辆信息完成...");
        return true;
    }

    /**
     * 公证抵押信息录入
     * @param generalNotaryMortgageBO
     * @return
     * @throws SuzukiCommonException
     */
    @Override
    @Transactional
    public Boolean inputNotaryMortgage(GeneralNotaryMortgageBO generalNotaryMortgageBO) throws SuzukiCommonException {
        log.info("开始录入公证抵押信息...");
        //插入新数据
        NotaryMortgageDO notaryMortgageDO = new NotaryMortgageDO();
        BeanCopierUtil.copy(generalNotaryMortgageBO, notaryMortgageDO);
        if(generalNotaryMortgageBO.getMortgageId()==null){
            log.info("新增公证抵押信息...");
            notaryMortgageDO.setIsDeleted(IsDeletedEnum.NORMAL.getCode());
            if( notaryMortgageExtMapper.insertSelective(notaryMortgageDO) != 1) {
                throw new SuzukiCommonException(ErrorCodeEnum.INSERT_OR_UPDATA_ERROR);
            }
        }else {
            log.info("更新公证抵押信息...");
            if (notaryMortgageExtMapper.updateByPrimaryKeySelective(notaryMortgageDO) != 1) {
                throw new SuzukiCommonException(ErrorCodeEnum.INSERT_OR_UPDATA_ERROR);
            }
        }
        log.info("录入出险信息完成...");
        return true;
    }


    /**
     * 合同齐全信息录入
     * @param generalContractSubmitBO
     * @return
     */
    @Override
    @Transactional
    public Boolean inputCotractSubmit(GeneralContractSubmitBO generalContractSubmitBO) throws SuzukiCommonException{
        log.info("开始录入合同齐全信息...");
        ContractSubmitDO contractSubmitDO = new ContractSubmitDO();
        BeanCopierUtil.copy(generalContractSubmitBO, contractSubmitDO);
        contractSubmitDO.setIsDeleted(IsDeletedEnum.NORMAL.getCode());
        if(generalContractSubmitBO.getContractSubmitId()==null){
            log.info("新增合同齐全信息...");
            contractSubmitDO.setIsDeleted(IsDeletedEnum.NORMAL.getCode());
            if ( contractSubmitExtMapper.insertSelective(contractSubmitDO) != 1) {
                throw new SuzukiCommonException(ErrorCodeEnum.INSERT_OR_UPDATA_ERROR);
            }
        }else {
            log.info("更新合同齐全信息...");
            if (contractSubmitExtMapper.updateByPrimaryKeySelective(contractSubmitDO) != 1) {
                throw new SuzukiCommonException(ErrorCodeEnum.INSERT_OR_UPDATA_ERROR);
            }
        }
        log.info("录入合同齐全信息完成...");
        return true;
    }

    /**
     * 寄卡信息录入
     * @param generalPostBankCardBO
     * @return
     */
    @Override
    @Transactional
    public Boolean inputPostBankCard(GeneralPostBankCardBO generalPostBankCardBO) throws SuzukiCommonException{
        log.info("开始录入寄卡信息...");
        PostBankCardDO postBankCardDO = new PostBankCardDO();
        BeanCopierUtil.copy(generalPostBankCardBO, postBankCardDO);
        if(generalPostBankCardBO.getPostCardId()==null){
            log.info("新增寄卡信息...");
            postBankCardDO.setIsDeleted(IsDeletedEnum.NORMAL.getCode());
            if ( postBankCardExtMapper.insertSelective(postBankCardDO) != 1) {
                throw new SuzukiCommonException(ErrorCodeEnum.INSERT_OR_UPDATA_ERROR);
            }
        }else {
            log.info("更新寄卡信息...");
            if (postBankCardExtMapper.updateByPrimaryKeySelective(postBankCardDO) != 1) {
                throw new SuzukiCommonException(ErrorCodeEnum.INSERT_OR_UPDATA_ERROR);
            }
        }
        log.info("录入寄卡信息完成...");
        return true;
    }

    /**
     * 退保证金信息录入
     * @param generalRefundDepositBO
     * @return
     */
    @Override
    @Transactional
    public Boolean inputRefundDeposit(GeneralRefundDepositBO generalRefundDepositBO) throws SuzukiCommonException{
        log.info("开始录入退保证金信息...");
        RefundDepositDO refundDepositDO = new RefundDepositDO();
        BeanCopierUtil.copy(generalRefundDepositBO, refundDepositDO);
        if(generalRefundDepositBO.getRefundId()==null){
            log.info("新增退保证金信息...");
            refundDepositDO.setIsDeleted(IsDeletedEnum.NORMAL.getCode());
            if (refundDepositExtMapper.insertSelective(refundDepositDO) != 1) {
                throw new SuzukiCommonException(ErrorCodeEnum.INSERT_OR_UPDATA_ERROR);
            }
        }else {
            log.info("更新退保证金信息...");
            if (refundDepositExtMapper.updateByPrimaryKeySelective(refundDepositDO) != 1) {
                throw new SuzukiCommonException(ErrorCodeEnum.INSERT_OR_UPDATA_ERROR);
            }
        }
        log.info("录入退保证金信息完成...");
        return true;
    }


    /**
     * 结清信息录入
     * @param generalLoanClearBO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean inputLoanClear(GeneralLoanClearBO generalLoanClearBO) throws SuzukiCommonException{
        log.info("开始录入结清信息...");
        LoanClearDO loanClearDO = new LoanClearDO();
        BeanCopierUtil.copy(generalLoanClearBO, loanClearDO);
        if(generalLoanClearBO.getClearId()==null){
            log.info("新增结清信息...");
            loanClearDO.setIsDeleted(IsDeletedEnum.NORMAL.getCode());
            if (loanClearExtMapper.insertSelective(loanClearDO) != 1) {
                throw new SuzukiCommonException(ErrorCodeEnum.INSERT_OR_UPDATA_ERROR);
            }
        }else {
            log.info("更新结清信息...");
            if (loanClearExtMapper.updateByPrimaryKeySelective(loanClearDO) != 1) {
                throw new SuzukiCommonException(ErrorCodeEnum.INSERT_OR_UPDATA_ERROR);
            }
        }
        log.info("录入结清信息完成...");
        return true;
    }

    /**
     * 保险信息录入
     * @param generalInsuranceInfoBOS
     * @return
     * @throws SuzukiCommonException
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean inputInsurance(List<GeneralInsuranceInfoBO> generalInsuranceInfoBOS) throws SuzukiCommonException{
        log.info("开始录入保险信息...");
        Iterator<GeneralInsuranceInfoBO> iterator = generalInsuranceInfoBOS.iterator();
        while(iterator.hasNext()){
            GeneralInsuranceInfoBO generalInsuranceInfoBO = iterator.next();
            InsuranceInfoDO insuranceInfoDO = new InsuranceInfoDO();
            BeanCopierUtil.copy(generalInsuranceInfoBO, insuranceInfoDO);
            if(generalInsuranceInfoBO.getInsId()==null){
                log.info("开始新增保险信息...");
                insuranceInfoDO.setIsDeleted(IsDeletedEnum.NORMAL.getCode());   //正常
                if( insuranceInfoExtMapper.insertSelective(insuranceInfoDO) != 1) {
                    throw new SuzukiCommonException(ErrorCodeEnum.INSERT_OR_UPDATA_ERROR);
                }
            }else {
                log.info("开始更新保险信息...");
                if( insuranceInfoExtMapper.updateByPrimaryKeySelective(insuranceInfoDO) != 1) {
                    throw new SuzukiCommonException(ErrorCodeEnum.INSERT_OR_UPDATA_ERROR);
                }
            }
        }
        log.info("录入保险信息完成...");
        return true;
    }


    /**
     * 综合处理选择保险公司
     * @param dataDictBO
     * @param logedUser
     * @return
     * @throws SuzukiCommonException
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<DataDictVO> getInsuranceCompanyList(DataDictBO dataDictBO,User logedUser) throws SuzukiCommonException{
        //验证该分组是否存在
        log.info("正在验证分组{}是否存在...",dataDictBO.getDataGroup());
        int size = iDataDictService.getCodeGroupByGroupCodeAndCompanyId(dataDictBO.getDataGroup(), logedUser.getCompanyNo());
        if(size == 1){
            log.info("分组存在...");
            Map<String, Object> paramMap = new HashMap<>(64);
            paramMap.put("companyNo", logedUser.getCompanyNo());              //公司
            paramMap.put("name", dataDictBO.getName());                      //数据名称
            paramMap.put("isDeleted", IsDeletedEnum.NORMAL.getCode());       //未删除
            paramMap.put("dataGroup",dataDictBO.getDataGroup());             //分组
            log.info("正在获取保险公司数据...");
            List<DataDictVO> dataDictVO = dataDictExtMapper.selectByInsuranceCompanyList(paramMap);
            log.info("保险公司数据为{}", JSON.toJSONString(dataDictVO));
            return dataDictVO;
        } else {
            throw new SuzukiCommonException(ErrorCodeEnum.DATA_ERROR);
        }
    }

}
